package com.aduerr.v1shouyin.mvp.activity;

import android.app.DatePickerDialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.GetDepositReportEntity;
import com.aduerr.v1shouyin.entity.PreAuthoOrderListEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.adpter.PreAuthoRecordAdapter;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2019/4/16 10:19
 * @change
 * @chang time
 * @class describe
 */

public class PreAuthoOrderRecord extends AppCompatActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_count_01)
    TextView tvCount01;
    @BindView(R.id.view_01)
    View view01;
    @BindView(R.id.ll_pre_autho_type01)
    LinearLayout llPreAuthoType01;
    @BindView(R.id.tv_count_02)
    TextView tvCount02;
    @BindView(R.id.view_02)
    View view02;
    @BindView(R.id.ll_pre_autho_type02)
    LinearLayout llPreAuthoType02;
    @BindView(R.id.tv_count_03)
    TextView tvCount03;
    @BindView(R.id.view_03)
    View view03;
    @BindView(R.id.ll_pre_autho_type03)
    LinearLayout llPreAuthoType03;
    @BindView(R.id.tv_count_00)
    TextView tvCount00;
    @BindView(R.id.view_00)
    View view00;
    @BindView(R.id.ll_pre_autho_type00)
    LinearLayout llPreAuthoType00;
    @BindView(R.id.tv_count_04)
    TextView tvCount04;
    @BindView(R.id.view_04)
    View view04;
    @BindView(R.id.ll_pre_autho_type04)
    LinearLayout llPreAuthoType04;
    @BindView(R.id.rl_no_data)
    RelativeLayout rlNoData;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.tv_yesterday)
    TextView mTvYesterday;
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.tv_tomorrow)
    TextView mTvTomorrow;

    private PreAuthoRecordAdapter preAuthoRecordAdapter;
    private List<PreAuthoOrderListEntity.DataBean> listAll = new ArrayList<>();
    private String orderType = "1";
    private int page = 1;

    private Drawable ivArrowGrey;
    private Drawable ivArrowWhite;
    private int mYear, mMonth, mDay;
    private Calendar ca;
    private SimpleDateFormat sDateFormat;


    /**
     * 日期选择器对话框监听
     */
    private DatePickerDialog.OnDateSetListener onDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear,
                                      int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    String days;
                    if(mMonth + 1 < 10) {
                        if(mDay < 10) {
                            days = new StringBuffer().append(mYear).append("-").append("0").
                                    append(mMonth + 1).append("-").append("0").append(mDay).toString();
                        } else {
                            days = new StringBuffer().append(mYear).append("-").append("0").
                                    append(mMonth + 1).append("-").append(mDay).toString();
                        }

                    } else {
                        if(mDay < 10) {
                            days = new StringBuffer().append(mYear).append("-").
                                    append(mMonth + 1).append("-").append("0").append(mDay).toString();
                        } else {
                            days = new StringBuffer().append(mYear).append("-").
                                    append(mMonth + 1).append("-").append(mDay).toString();
                        }

                    }
                    mTvDate.setText(days);
                    getData();
                    getOrderList(orderType,1);
                    if(mTvTomorrow.getText().toString().equals(sDateFormat.format(System.currentTimeMillis()))) {
                        mTvTomorrow.setClickable(false);
                        mTvTomorrow.setCompoundDrawables(null, null, ivArrowGrey, null);
                        mTvTomorrow.setTextColor(getResources().getColor(R.color.font_value));
                    } else {
                        mTvTomorrow.setClickable(true);
                        mTvTomorrow.setCompoundDrawables(null, null, ivArrowWhite, null);
                        mTvTomorrow.setTextColor(getResources().getColor(R.color.white));
                    }
                }
            };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pre_autho_record);
        ButterKnife.bind(this);
        tvTitle.setText("预授权订单");
        initView();
        preAuthoRecordAdapter = new PreAuthoRecordAdapter(this, listAll);

        recyclerview.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false));
        DividerItemDecoration divider = new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL);
        divider.setDrawable(getResources().getDrawable(R.drawable.divider));
        recyclerview.addItemDecoration(divider);
        recyclerview.setAdapter(preAuthoRecordAdapter);
        refreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getOrderList(orderType, 1);
                        getData();
                        refreshlayout.finishRefresh();
                    }
                }, 1500);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getOrderList(orderType, page + 1);
                        getData();
                        refreshlayout.finishLoadmore();

                    }
                }, 1500);
            }
        });


    }


    public void initView() {
        ca = Calendar.getInstance();
        sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);
        ivArrowGrey = getResources().getDrawable(R.drawable.img_arrow_right_g);
        ivArrowWhite = getResources().getDrawable(R.drawable.img_arrow_right_w);
        ivArrowGrey.setBounds(0, 0, ivArrowGrey.getMinimumWidth(),
                ivArrowGrey.getMinimumHeight());
        ivArrowWhite.setBounds(0, 0, ivArrowWhite.getMinimumWidth(),
                ivArrowWhite.getMinimumHeight());
        mTvDate.setText(new StringBuffer().append(mYear).append("-").
                append(mMonth + 1).append("-").append(mDay).toString());
        mTvTomorrow.setClickable(false);
        mTvTomorrow.setCompoundDrawables(null, null, ivArrowGrey, null);
        mTvTomorrow.setTextColor(getResources().getColor(R.color.font_value));

    }


    @Override
    protected void onResume() {
        super.onResume();
     /*   getOrderList(orderType, 1);
        getData();*/
        //触发自动刷新
        refreshLayout.autoRefresh();
    }

    @OnClick({R.id.img_back, R.id.ll_pre_autho_type01, R.id.ll_pre_autho_type02,
            R.id.ll_pre_autho_type03, R.id.ll_pre_autho_type00,
            R.id.ll_pre_autho_type04, R.id.tv_yesterday, R.id.tv_date, R.id.tv_tomorrow})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.ll_pre_autho_type01:
                orderType = "1";
                getOrderList("1", 1);
                view00.setVisibility(View.GONE);
                view01.setVisibility(View.VISIBLE);
                view02.setVisibility(View.GONE);
                view03.setVisibility(View.GONE);
                view04.setVisibility(View.GONE);
                break;
            case R.id.ll_pre_autho_type02:
                orderType = "2";
                getOrderList("2", 1);
                view00.setVisibility(View.GONE);
                view01.setVisibility(View.GONE);
                view02.setVisibility(View.VISIBLE);
                view03.setVisibility(View.GONE);
                view04.setVisibility(View.GONE);
                break;
            case R.id.ll_pre_autho_type03:
                orderType = "3";
                getOrderList("3", 1);
                view00.setVisibility(View.GONE);
                view01.setVisibility(View.GONE);
                view02.setVisibility(View.GONE);
                view03.setVisibility(View.VISIBLE);
                view04.setVisibility(View.GONE);
                break;
            case R.id.ll_pre_autho_type00:
                orderType = "0";
                getOrderList("0", 1);
                view00.setVisibility(View.VISIBLE);
                view01.setVisibility(View.GONE);
                view02.setVisibility(View.GONE);
                view03.setVisibility(View.GONE);
                view04.setVisibility(View.GONE);
                break;
            case R.id.ll_pre_autho_type04:
                orderType = "4";
                getOrderList("4", 1);
                view00.setVisibility(View.GONE);
                view01.setVisibility(View.GONE);
                view02.setVisibility(View.GONE);
                view03.setVisibility(View.GONE);
                view04.setVisibility(View.VISIBLE);
                break;

            case R.id.tv_yesterday:
                mTvDate.setText(subDay(mTvDate.getText().toString()));
                if(mTvDate.getText().toString().equals(sDateFormat.format(System.currentTimeMillis()))) {
                    mTvTomorrow.setClickable(false);
                    mTvTomorrow.setCompoundDrawables(null, null, ivArrowGrey, null);
                    mTvTomorrow.setTextColor(getResources().getColor(R.color.font_value));
                } else {
                    mTvTomorrow.setClickable(true);
                    mTvTomorrow.setCompoundDrawables(null, null, ivArrowWhite, null);
                    mTvTomorrow.setTextColor(getResources().getColor(R.color.white));
                }
                getData();
                getOrderList(orderType,1);
                break;

            case R.id.tv_tomorrow:
                mTvDate.setText(addDay(mTvDate.getText().toString()));
                if(mTvDate.getText().toString().equals(sDateFormat.format(System.currentTimeMillis()))) {
                    mTvTomorrow.setClickable(false);
                    mTvTomorrow.setCompoundDrawables(null, null, ivArrowGrey, null);
                    mTvTomorrow.setTextColor(getResources().getColor(R.color.font_value));
                } else {
                    mTvTomorrow.setClickable(true);
                    mTvTomorrow.setCompoundDrawables(null, null, ivArrowWhite, null);
                    mTvTomorrow.setTextColor(getResources().getColor(R.color.white));
                }
                getData();
                getOrderList(orderType,1);
                break;
            case R.id.tv_date:
                showDatePick(mTvDate.getText().toString());
                break;

        }
    }

    void showDatePick(String date) {
        try {
            Date d = sDateFormat.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(d);
            DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                    DatePickerDialog.THEME_DEVICE_DEFAULT_LIGHT, onDateSetListener,
                    calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH));
            datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
            datePickerDialog.show();
        } catch(ParseException e) {
            e.printStackTrace();
        }

    }


    //0预授权未支付1预授权冻资中2预授权完成3预授权撤销4预授权完成撤销
    private void getOrderList(String orderType, int index) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("beginTime", mTvDate.getText().toString());
        addParams.put("endTime", addDay(mTvDate.getText().toString()));
        addParams.put("type", "1");
        addParams.put("OrderState", orderType);
        addParams.put("PageIndex", index + "");
        APIRetrofit.getAPIService().getPreAuthoOrderList(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(entity -> {
                    if(entity.getSuccess() == 1) {
                        page = entity.getPageIndex();
                        if(page == 1 && entity.getData().size() == 0) {
                            rlNoData.setVisibility(View.VISIBLE);
                            refreshLayout.setVisibility(View.GONE);
                        } else {
                            if(page == 1) {
                                preAuthoRecordAdapter.clearData();
                            }
                            rlNoData.setVisibility(View.GONE);
                            refreshLayout.setVisibility(View.VISIBLE);
                            preAuthoRecordAdapter.addData(entity.getData());
                        }
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    ToastUtils.showToast(this, "网络异常");
                });

    }

    private void getData() {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("beginTime", mTvDate.getText().toString());
        addParams.put("endTime", addDay(mTvDate.getText().toString()));
        addParams.put("type", "1");
        APIRetrofit.getAPIService().getDepositReport(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(entity -> {
                    if(entity.getSuccess() == 1) {
                        GetDepositReportEntity.DataBean data = entity.getData();
                        tvCount01.setText(data.getDepositCount() + "笔");
                        tvCount02.setText(data.getFinishCount() + "笔");
                        tvCount03.setText(data.getCancelCount() + "笔");
                        tvCount04.setText(data.getFinishCancelCount() + "笔");
                        tvCount00.setText(data.getNotPayCount() + "笔");
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    ToastUtils.showToast(this, "网络异常");
                });
    }


    public String addDay(String currentDay) {

        Date date = null;
        try {
            date = (new SimpleDateFormat("yyyy-MM-dd")).parse(currentDay);
        } catch(ParseException e) {
            e.printStackTrace();
        }

        Calendar cal = Calendar.getInstance();

        cal.setTime(date);

        cal.add(Calendar.DATE, 1);

        date = cal.getTime();

        return (new SimpleDateFormat("yyyy-MM-dd")).format(date);
    }

    public String subDay(String currentDay) {

        Date date = null;
        try {
            date = (new SimpleDateFormat("yyyy-MM-dd")).parse(currentDay);
        } catch(ParseException e) {
            e.printStackTrace();
        }

        Calendar cal = Calendar.getInstance();

        cal.setTime(date);

        cal.add(Calendar.DATE, -1);

        date = cal.getTime();

        return (new SimpleDateFormat("yyyy-MM-dd")).format(date);
    }
}
